package com.zero.servlet;

import com.zero.domain.User;
import com.zero.service.IUserLoginService;
import com.zero.service.impl.UserLoginServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名"+ username);
        System.out.println("密码"+ password);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        IUserLoginService userLoginService = new UserLoginServiceImpl();
        boolean istrue = userLoginService.login(user);
        if(istrue){
            Cookie userNameCo= new Cookie("username", username);
            userNameCo.setMaxAge(60*60*24*30);
            response.addCookie(userNameCo);

            Cookie userPwdCo= new Cookie("userpwd", password);
            userPwdCo.setMaxAge(60*60*24*30);
            response.addCookie(userPwdCo);

            HttpSession session = request.getSession();// 创建Session
            // session.setMaxInactiveInterval(10);//设置失效时间10秒 不是销毁
            ServletContext servletContext = getServletContext();
            Object num = servletContext.getAttribute("num");
            System.out.println("在线人数:" + num);

            response.sendRedirect("/servletdemo/home.html");

        }else {
            response.getWriter().println("错误的用户名和密码");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
